package com.example.treasureadmin.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.treasureadmin.entity.MsgEntity;
import com.example.treasureadmin.model.ManagerModel;
import com.example.treasureadmin.service.ManagerService;
import com.example.treasureadmin.shiroentity.auth.AuthUser;
import com.example.treasureadmin.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

// 接收请求
@RestController
@RequestMapping("/treasure-admin")
public class ManagerController {

    @Autowired
    private ManagerService managerService;
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public MsgEntity login(@RequestBody JSONObject requestBody){
        String username = requestBody.getString("username");
        String password = requestBody.getString("password");//alt+enter
        String code = managerService.login(username, password);
        if(code.equals("200")){
            HashMap<String, Object> map = new HashMap<>();
            map.put("username",username);
            String token = jwtUtils.encode(username, 3 * 24 * 60 * 60 * 1000, map);
            return new MsgEntity("200","SUCCESS",token);
        }
        else{
            return new MsgEntity("101","ERROR","用户名或者密码错误");
        }
    }

    @PostMapping("/relogin")
    public MsgEntity relogin(@AuthUser String username){
        ManagerModel relogin = managerService.relogin(username);
        return new MsgEntity("200","SUCCESS",relogin);

    }
}
